package com.mall.cart.interceptor;

import com.mall.cart.dto.UserInfoDto;
import com.mall.common.constant.AuthorConstant;
import com.mall.common.dto.MemberDTO;
import com.mall.common.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author: 谢君臣
 * @Date: 2022/8/8-14:26
 * @version: 1.0
 * @function:
 */
@Component
public class CartIndexInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoDto> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoDto userInfoDto = new UserInfoDto();
        HttpSession session = request.getSession();
        UserInfoVo userInfoVo = (UserInfoVo) session.getAttribute(AuthorConstant.LOGIN_USER);
        if (userInfoVo!=null) // 登录用户
        {
            userInfoDto.setUserId(userInfoVo.getId());
            userInfoDto.setTemp(false);
        }
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthorConstant.USER_KEY)) {
               userInfoDto.setUserKey(cookie.getValue());
            }
        }
        // 没有临时用户
        if (StringUtils.isEmpty(userInfoDto.getUserKey()))
        {
            String uuid = UUID.randomUUID().toString();
            userInfoDto.setUserKey(uuid);
        }
        threadLocal.set(userInfoDto);
        return true;
    }
}
